package dave.hibernate.lab;


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Blob;
import java.sql.SQLException;

import javax.persistence.Embeddable;

import org.hibernate.Hibernate;

@Embeddable
public class BlodHandler implements Serializable {
	byte[] image; 
	public byte[] getImage() {  return image; } 
	public void setImage(byte[] image) {  this.image = image; }
	
	/** Don't invoke this.  Used by Hibernate only. */ 
	public void setImageBlob(Blob imageBlob) {  this.image = this.toByteArray(imageBlob); }
	
	/** Don't invoke this.  Used by Hibernate only. */ 
	@SuppressWarnings("deprecation")
	public Blob getImageBlob() {  return Hibernate.createBlob(this.image); }
	
	private byte[] toByteArray(Blob fromBlob) {  
		ByteArrayOutputStream baos = new ByteArrayOutputStream();  
		try {   
			return toByteArrayImpl(fromBlob, baos);  
		} 
		catch (SQLException e) {   throw new RuntimeException(e);  } 
		catch (IOException e) {   throw new RuntimeException(e);  } 
		finally {   
			if (baos != null) {    
				try {     baos.close();    } 
				catch (IOException ex) {    }   
			}//end if
		}//end finally
	}//end toByteArray
	
	
	private byte[] toByteArrayImpl(Blob fromBlob, ByteArrayOutputStream baos)  throws SQLException, IOException {  
		byte[] buf = new byte[4000];
		InputStream is = fromBlob.getBinaryStream();
		try {   
			for (;;) {    
				int dataSize = is.read(buf);    
				if (dataSize == -1)     
					break;    
				baos.write(buf, 0, dataSize);   
			}//end for  
		}//end try
		
		finally {   
			if (is != null) {    
				try {     
					is.close();    
				} catch (IOException ex) {    }   
			}//end if  
		}//end finally
		
		return baos.toByteArray();
	}//end toByteArrayImpl
}